import axios from 'axios'
import store from '@/store/index.js'

import router from '@/router/index.js'

const request = axios.create({
  baseURL: 'http://www.liulongbin.top:3008'
})
// 定义请求拦截器
request.interceptors.request.use((config) => {
  // 为请求头挂载 Authorization 字段
  if (config.url.startsWith('/my')) {
    config.headers.Authorization = store.state.token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})
// 定义响应拦截器
// Add a response interceptor
request.interceptors.response.use((response) => {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  return response
}, (error) => {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  // console.dir(error)
  if (error.response.status === 401) {
    // token 无效，清空token 并重新登录
    store.commit('updateToken', '')
    router.push('/login')
  }
  return Promise.reject(error)
})

export default request
